#ifndef SERVER_H
#define SERVER_H

#include <boost\asio.hpp>
#include <boost\shared_ptr.hpp>
#include <boost\bind.hpp>
#include <boost\noncopyable.hpp>
#include "session.h"


namespace comunication {

	class server: public boost::noncopyable
	{
	public:
		server(io_service& service, const tcp::endpoint& endpoint):
			io_service_(service), acceptor_(io_service_, endpoint)
		{
			start_accept();
		}

		void start_accept()
		{
			if(!session_ptr || !session_ptr->is_client_connected()) {
				session_ptr.reset(new session(io_service_));
				acceptor_.async_accept(session_ptr->socket(),
					boost::bind(&server::handle_accept, this, session_ptr,
					boost::asio::placeholders::error));
			}
		}

		void handle_accept(boost::shared_ptr<session> ptr,
			const boost::system::error_code& error)
		{
			if (!error) {
				ptr->start();
			}

			start_accept();
		}

	private:
		io_service& io_service_;
		tcp::acceptor acceptor_;
		boost::shared_ptr<session> session_ptr;
	};
}
#endif